package com.antler.smt.portal.service.impl;

import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.LevelConstant;
import com.antler.smt.entity.*;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.*;
import com.antler.smt.portal.utils.RedisUtil;
import com.antler.smt.request.admin.GetPurchaserListReq;
import com.antler.smt.request.portal.PurchaserPersonReq;
import com.antler.smt.response.admin.GetOrderListResp;
import com.antler.smt.response.admin.GetPurchaserListResp;
import com.antler.smt.response.admin.GetUserListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.response.portal.GetImgResp;
import com.antler.smt.service.portal.PurchaserService;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *  采购商实现接口
 *
 * @author zhangyi
 * @date 2018/3/27 13:03
 */
@Service
public class PurchaserServiceImpl implements PurchaserService {

    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Autowired
    private PurchaserInfoMapper purchaserInfoMapper;

    @Autowired
    private MemberEntityMapper memberEntityMapper;

    @Autowired
    private PurchaserEntityMapper purchaserEntityMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    @Autowired
    private AttachmentEntityMapper attachmentEntityMapper;

    @Autowired
    private PurchaserAccountInfoMapper purchaserAccountInfoMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     *  获取采购商实体
     *
     * @param memberId 会员Id
     * @return
     */
    @Override
    public Result<GetPurchaserListResp> getPurchaserInfo(long memberId) {
        Result result = null;

        //获取采购商实体
        GetPurchaserListResp purchaserInfo = purchaserInfoMapper.selectByMemberId(memberId);

        //获取会员实体
        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(memberId);

        List resultInfoList = new ArrayList();

        resultInfoList.add(purchaserInfo);
        resultInfoList.add(memberEntity);

        result = new Result(resultInfoList);
        return result;
    }

    /**
     * 获取其采购商全部订单列表
     *
     * @param memberId 获取其登陆实体
     * @return
     */
    @Override
    public Result<GetOrderListResp> purchaserOrderList(long memberId) {

        Result result = null;

        //获取采购商订单列表
        List<GetOrderListResp> orderList = orderInfoMapper.selectOrderByMember(memberId);

        List<GetOrderListResp> list = new ArrayList<>();

        for (GetOrderListResp order : orderList) {

            //项目专员id
            Long connectUserId = order.getConnectUserId();

            //服务商id
            Long supplierId = order.getSupplierId();
            //项目专员实体
            GetUserListResp userInfo = userInfoMapper.getUserInfo(connectUserId);
            //商务专员id
            Long businessAffairsUserId = order.getBusinessAffairsUserId();

            if(null != userInfo) {
                //插入真实姓名
                order.setRealName(userInfo.getRealName());
            }
            GetUserListResp businessUserInfo = userInfoMapper.getUserInfo(businessAffairsUserId);
            if(null  != businessUserInfo) {
                order.setBusinessUserName(businessUserInfo.getRealName());
            }
            //报告文件名id
            Long reportId = order.getTestReportAttachmentId();

            AttachmentEntity attachmentEntity = attachmentEntityMapper.selectByPrimaryKey(reportId);

            //添加报告名
            if(null != attachmentEntity){
                order.setReportName(attachmentEntity.getFileName());
            }

            if(order.getStatus() != 100) {

                SupplierEntity supplierEntity = supplierEntityMapper.selectByPrimaryKey(supplierId);

                if(null != supplierEntity) {
                    //服务商用户实体
                    MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(supplierEntity.getMemberId());
                    //插入服务商昵称
                    order.setNickName(memberEntity.getNickName());
                }else {
                    order.setNickName(null);
                }
            }
            list.add(order);

        }
        result = new Result(list);

        return result;
    }

    /**
     *  采购商认证
     *
     * @param request 实体获取
     * @param memberId 当前护会员id
     * @param code 验证码
     * @return
     */
    @Override
    public Result<ResultCodeEnum> purchaserCertification(GetPurchaserListReq request,Long memberId,String code) {

        Result result = null;
        //采购商实体
        PurchaserEntity purchaserEntity = new PurchaserEntity();

        //添加会员id
        purchaserEntity.setMemberId(memberId);

        //添加公司名称
        purchaserEntity.setCompanyName(request.getCompanyName());

        //统一信用社代码
        purchaserEntity.setCreditCode(request.getCreditCode());

        //添加公司地址
        purchaserEntity.setDetailAddress(request.getDetailAddress());

        //添加法人
        purchaserEntity.setLegalPerson(request.getLegalPerson());

        //添加成立日期
        purchaserEntity.setFoundTime(request.getFoundTime());

        //添加营业执照id
        purchaserEntity.setBusinessLicenseAttachmentId(request.getBusinessLicenseAttachmentId());

        //添加联系人
        purchaserEntity.setLinkMan(request.getLinkMan());

        //添加电子邮箱
        purchaserEntity.setLinkEmail(request.getLinkEmail());

        //添加联系电话
        purchaserEntity.setLinkPhone(request.getLinkPhone());

        //检测验证码
        String localCode = redisUtil.get(String.valueOf(memberId));

        //初始化审核状态  认证审核状态 0未申请 1已申请未审核 2审核通过 3审核未通过
        purchaserEntity.setAuditResult(1);

        // 添加审核申请时间
        purchaserEntity.setAuditTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //初始化时间
        purchaserEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
        purchaserEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //判断验证码
        if(localCode.equals(code)){
            //采购商写入
            int i = purchaserInfoMapper.updatePurchaserInfo(purchaserEntity);

            if(0 == i){
                result = new Result(ResultCodeEnum.APPEND_DATA_ERROR,"更新采购商认证信心失败！");
                //移除此验证码
                redisUtil.remove(code);

            }else{
                result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
            }
        }else {
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR,"验证码错误！");
        }
        return result;
    }

    /**
     * 返回认证详情信息
     *
     * @param memberId
     * @return
     */
    @Override
    public Result getCertificationInfo(Long memberId) {
        Result result = null;

        GetPurchaserListResp purchaserListResp = purchaserInfoMapper.selectAuditByMemberId(memberId);

        if(null != purchaserListResp){
            //已认证状态
            result = new Result(purchaserListResp);
        }else{
            //未认证状态
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR,"该采购商未认证！");
        }

        return result;
    }

    /**
     * 获取该采购商下的营业执照图片
     *
     * @param memberId
     * @return
     */
    @Override
    public Result<GetImgResp> getCertificationImg(Long memberId) {
        Result result = null;

        GetPurchaserListResp purchaserListResp = purchaserInfoMapper.selectByMemberId(memberId);


        //获取营业执照信息
        AttachmentEntity attachmentEntity = attachmentEntityMapper.selectByPrimaryKey(purchaserListResp.getBusinessLicenseAttachmentId());

        GetImgResp getImgResp = new GetImgResp();
        getImgResp.setImgName(attachmentEntity.getFileName());

        result = new Result(getImgResp);

        return result;
    }

    /**
     * 计算距离下次升级此采购商所需要的金额
     *
     * @param memberId
     * @return
     */
    @Override
    public Result nextGoUpMoney(Long memberId) {
        Result result = null;

        //获取星级
        Integer starLevel = purchaserInfoMapper.getStarLevel(memberId);
        //审核后的充值总金额
        Long allAuditMoney = purchaserInfoMapper.getAllAuditMoney(memberId);
        //消费的总金额
        Long shopMoney = orderInfoMapper.getShopMoney(memberId);

        //获取星级
        Integer star = 1;

        //距离下次升级的金额
        Long money = new Long(0);

        if(null == allAuditMoney){
            allAuditMoney = new Long(0);
        }if(null == shopMoney){
            shopMoney = new Long(0);
        }

        Long allMoney = shopMoney+allAuditMoney;
        Integer starMoney = 0;

        while(money <= 0) {
            if (allMoney <= LevelConstant.TWO_STAR && (money = LevelConstant.TWO_STAR - allMoney) >= 0) {
                starMoney = 10000;
            } else if (allMoney <= LevelConstant.THREE_STAR && (money = LevelConstant.THREE_STAR - allMoney) >= 0) {
                starMoney = 100000;
                star = 2;
            } else if (allMoney <= LevelConstant.FOUR_STAR && (money = LevelConstant.FOUR_STAR - allMoney) >= 0) {
                starMoney = 500000;
                star = 3;
            } else if (allMoney <= LevelConstant.FIVE_STAR && (money = LevelConstant.FIVE_STAR - allMoney) >= 0) {
                starMoney = 800000;
                star = 4;
            } else if (allMoney >= LevelConstant.FIVE_STAR) {
                money = new Long(-1);
                starMoney = -1;
                star = 5;
            }
            //距离下次等级的金额大于升级的金额
            if (money > 0) {
                if(starLevel == 5){
                    money = new Long(-1);
                    starMoney = -1;
                    break;
                }else {
                    PurchaserAccountEntity accountEntity = new PurchaserAccountEntity();
                    accountEntity.setMemberId(memberId);
                    starLevel = star;
                    accountEntity.setVipLevel(starLevel);
                    purchaserAccountInfoMapper.updateStar(accountEntity);
                }
            }else{
                if(allMoney >= LevelConstant.FIVE_STAR){
                    money = new Long(-1);
                    starMoney = -1;
                    PurchaserAccountEntity accountEntity = new PurchaserAccountEntity();
                    accountEntity.setMemberId(memberId);
                    accountEntity.setVipLevel(5);
                    purchaserAccountInfoMapper.updateStar(accountEntity);
                    break;
                }
            }
        }
        Object[] array = new Object[]{money,starMoney};
        result = new Result(array);
        return result;
    }


    /**
     *  采购商编辑个人信息
     *
     * @param request 采购商个人信息实体
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> editPurchaserInfo(PurchaserPersonReq request,Long memberId) {
        Result result = null;

        //新建采购商实体
        PurchaserEntity purchaserEntity = new PurchaserEntity();

        //添加公司名称
        purchaserEntity.setCompanyName(request.getCompanyName());

        //统一信用社代码
        purchaserEntity.setCreditCode(request.getCreditCode());

        //添加公司地址
        purchaserEntity.setDetailAddress(request.getDetailAddress());

        //添加法人
        purchaserEntity.setLegalPerson(request.getLegalPerson());

        //添加成立日期
        purchaserEntity.setFoundTime(request.getFoundTime());

        //添加联系人
        purchaserEntity.setLinkMan(request.getLinkMan());

        //添加电子邮箱
        purchaserEntity.setCompanyEmail(request.getCompanyEmail());

        //添加联系电话
        purchaserEntity.setLinkPhone(request.getLinkPhone());

        //修改更新时间
        purchaserEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        GetPurchaserListResp getPurchaserListResp = purchaserInfoMapper.selectByMemberId(memberId);
        Long purchaserId = getPurchaserListResp.getId();

        //添加采购商主键
        purchaserEntity.setId(purchaserId);


        //创建会员实体
        MemberEntity memberEntity = new MemberEntity();

        //添加昵称
        memberEntity.setNickName(request.getNickName());

        //添加头像id
        memberEntity.setHeadImageAttachmentId(request.getHeadImageAttachmentId());

        //添加更新时间
        memberEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //添加会员主键
        memberEntity.setId(memberId);


        int i = purchaserEntityMapper.updateByPrimaryKeySelective(purchaserEntity);

        int i1 = memberEntityMapper.updateByPrimaryKeySelective(memberEntity);

        if((i & i1) == 0){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }

        return result;
    }
}
